//组织机构
function area_main() {
    var addDeptBefore = function (form) {
        var data = [];
        $.dic('organType').getData().each(function (row) {
            if (row.get('value') != 'area')
                data.push(row.getData());
        });
        form.get('organType').getStore().loadData(data);
    }
    return {
        dClick: function (cmp, r) {
            BasicOrganization_form().view({
                entityId: r.get('id')
            });
        },
        id: 'BasicOrganization_main',
        xtype: 'jtree',
        clazz: BasicOrganization,
        order: ['organSort->asc'],
        startId: USER.areaId,
        startSelf: true,
        loadFn: function (grid, rec) {
            grid.select(rec[0]);
        },
        top: [Ext.apply(Ext.clone($.treeSearch), {
            width: 200,
            emptyText: '检索组织机构名称'
        }), '->', {
            key: 'A',
            iconCls: ion.add,
            text: '添加组织机构',
            id: 'addBasicOrganization',
            handler: function () {
                var grid = $('BasicOrganization_main');
                BasicOrganization_form().save({
                    rk: {
                        msg: '选中一个上级后才能进行添加',
                        exp: ['id->organParentId.id'],
                        id: 'BasicOrganization_main'
                    },
                    before: function (form) {
                        addDeptBefore(form);
                        form.set('organCode', $.num('AREA'));
                    },
                    grid: ['BasicOrganization_main']
                });
            }
        }, {
            id: 'editBasicOrganization',
            key: 'E',
            iconCls: ion.edit,
            text: '修改组织机构',
            handler: function () {
                BasicOrganization_form(true).edit({
                    readOnlys: ['organCode'],
                    loadCallback: function (form) {
                        form.get('organName').setReadOnly(false);
                        var type = form.get('organType');
                        if (type.v() == 'area') {
                            type.getStore().loadData([{
                                text: '企业域',
                                value: 'area'
                            }]);
                            type.setValue('area');
                        }
                    },
                    before: addDeptBefore,
                    grid: ['BasicOrganization_main']
                });
            }
        }, {
            id: 'delBasicOrganization',
            key: 'D',
            iconCls: ion.del,
            text: '删除组织机构',
            handler: function () {
                $('BasicOrganization_main').deletes({
                    before: function (grid, row) {
                        if (grid.select()[0].get('organType') == 'area') {
                            return $.error('企业域不能删除!');
                        }
                    },
                    validate: [[BasicOrganization, 'organParentId.id', '组织机构{organName}存在下级，请先删除下级后再尝试.'],
                        [BasicRole, 'organId.id', '组织机构{organName}下存在角色，请先删除角色后再尝试.'],
                        [BasicPosition, 'organId.id', '组织机构{organName}存在岗位，请先岗位后再尝试.'],
                        [BasicUser, 'organId.id', '组织机构{organName}存在人员，请先删除人员后再尝试.'],
                        [BasicRoleOrganization, 'organId.id', '组织机构{organName}被分配了角色，请取消角色关联后再尝试.'],
                        [BasicPartTime, 'organId.id', '组织机构{organName}下存在兼职信息，请先清空后再尝试.']]
                });
            }
        }, {
            id: 'flowerOrganizationRole',
            iconCls: 'fa-flask',
            text: '分配角色',
            handler: function () {
                BasicOrganization_main_distribution_role();
            },
            cls: 'black'
        }],
        mapper: 'id,organName,organParentId.id,organType,organUserName,organTel,organUserPhone,organSort,memo',
        columns: [{
            width: 200,
            text: '组织机构名称',
            "name": "text",
            renderer: function (v) {
                return "<span class='label label-primary'>" + v + "</span>";
            }
        }, {
            text: '类型',
            "name": "organType",
            renderer: $.dicRenderer('organType')
        }, {
            width: 130,
            "name": "organTel",
            renderer: function (v) {
                return "<i class='fa-phone-square fa x-fa-logo'></i>&nbsp;&nbsp;" + v;
            }
        }, {
            text: '负责人',
            "name": "organUserName",
            renderer: function (v, m) {
                m.tdCls = 'td-gray';
                return v;
            }
        }, {
            width: 130,
            "name": "organUserPhone",
            renderer: function (v, m) {
                m.tdCls = 'td-gray';
                return v;
            }
        }, {
            flex: 1,
            "name": "memo"
        }]
    }
}

function BasicOrganization_form(edit) {
    var sel = $('BasicOrganization_main').select()[0], ws = [];
    if (sel && edit) {
        ws = [['id', '!=', sel.get('id')]];
    }
    return $({
        id: 'BasicOrganization_form',
        xtype: 'jform',
        clazz: BasicOrganization,
        hides: ['createDate', {
            'createUser.id': USER.userId
        }],
        validate: [['organName = ? , organParentId.id = ?', 'organName', '名称不能重复']],
        fieldsSize: 0.5,
        defaults: {
            lw: 100
        },
        fields: [{
            text: '点击上传组织机构图片',
            xtype: 'imgfield',
            name: 'organImg'
        }, {
            name: 'organType',
            xtype: 'combo',
            value: 'dept',
            store: $.dic('organType'),
            req: true
        }, {
            text: '上级组织机构',
            name: 'organParentId.id',
            xtype: 'jselecttree',
            tree: {
                startId: USER.areaId,
                startSelf: true,
                where: ws,
                clazz: BasicOrganization,
                mapper: 'id,organName,organParentId.id'
            }
        }, {
            value: 1,
            minValue: 0,
            xtype: 'numberfield',
            "name": "organSort"
        }, {
            req: true,
            "name": "organCode",
            readOnly: true
        }, {
            req: true,
            "name": "organName"
        }, {
            req: true,
            name: 'organUserName'
        }, {
            req: true,
            vtype: 'phone',
            name: 'organUserPhone'
        }, {
            req: true,
            vtype: 'tel_phone',
            name: 'organTel'
        }, {
            req: true,
            name: 'memo',
            xtype: 'textarea',
            size: 1
        }]
    })
}

// 角色分配
function BasicOrganization_main_distribution_role() {
    var sel = $('BasicOrganization_main').select()[0];
    if (!sel) {
        return $.error('请选中一个组织机构后再进行角色分配');
    }
    var node = null;
    sel.bubble(function (n) {
        node = n;
        return !(node.get('organType') == 'area')
    });
    var name = sel.get('text'), id = sel.get('id');
    $.orm.getMtm({
        tagerFields: ['roleId'],
        clazz: BasicRoleOrganization,
        src: 'organId',
        srcId: id,
        callback: function (data) {
            var form = $({
                width: 450,
                xtype: 'jform',
                defaults: {
                    lw: 100
                },
                fields: [{
                    text: '组织机构',
                    value: name,
                    readOnly: true
                }, {
                    xtype: 'itemselector',
                    height: 250,
                    value: data.rid,
                    displayField: 'roleName',
                    valueField: 'id',
                    id: 'basic_organization_role_itemselector',
                    store: $.store({
                        clazz: BasicRole,
                        fields: ['roleName', 'id'],
                        where: [['roleType', '=', '2'], ['organId.id', '=', node.get('id')]]
                    }),
                    text: '组织机构角色'
                }]
            });
            form.win({
                buttons: [{
                    text: '完成',
                    cls: 'green',
                    iconCls: 'fa-hand-o-down',
                    handler: function () {
                        $.orm.mtm({
                            clazz: BasicRoleOrganization,
                            src: 'organId',
                            srcId: id,
                            infos: [{
                                tagerField: 'roleId',
                                ids: $('basic_organization_role_itemselector').v().join(',')
                            }],
                            callback: function () {
                                $.show(Ext.String.format('组织机构【{0}】的角色已成功分配', name));
                                form.win.close();
                            }
                        });
                    }
                }],
                title: Ext.String.format('为【{0}】分配角色', name)
            });
        }
    });

}
